//
//  UIToolsControl.m
//  Btpin
//
//  Created by Vic on 2019/3/10.
//  Copyright © 2019 Vic. All rights reserved.
//


#import "UIToolsControl.h"
#import "SigninViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <CoreImage/CoreImage.h>
#import <sys/utsname.h>
//#import "RSAEncryptor.h"

#import <WXApi.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>

@implementation UIToolsControl

// 设置渐变
+ (CAGradientLayer *)initWithFrame:(CGRect)frame fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = frame;
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)fromColor.CGColor,(__bridge id)toColor.CGColor];
    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
//    gradientLayer.startPoint = CGPointMake(0, 0.5);
//    gradientLayer.endPoint = CGPointMake(1, 0.5);
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0, @1];
    return gradientLayer;
}

+ (UILabel *)initLabelWithFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)color font:(NSInteger)font {
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    if (font) {
        label.font = Font(font);
    }
    if (color) {
        label.textColor = color;
    }
    if (text) {
        label.text = text;
    }
    return label;
}
+ (UIView *)initViewWithFrame:(CGRect)frame backgroundColor:(UIColor *)color cornerRadius:(CGFloat)cornerRadius borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth shadowOffset:(CGSize)shadowOffset shadowOpacity:(CGFloat)shadowOpacity shadowRadius:(CGFloat)shadowRadius shadowColor:(UIColor *)shadowColor {
    UIView *bgView = [[UIView alloc] initWithFrame:frame];
    bgView.backgroundColor = color;
    
    UIView *view = [[UIView alloc] initWithFrame:bgView.bounds];
    view.backgroundColor = COLOR_OF_WHITE;
    //圆角
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = cornerRadius;
    [bgView addSubview:view];
    
    // 阴影
    CALayer *subLayer = [CALayer layer];
    CGRect fixframe = view.frame;
    subLayer.frame = fixframe;
    subLayer.cornerRadius = cornerRadius;
    subLayer.backgroundColor = COLOR_OF_WHITE.CGColor;
    subLayer.masksToBounds = NO;
    subLayer.shadowColor = shadowColor.CGColor;//shadowColor阴影颜色
    subLayer.shadowOffset = shadowOffset;//shadowOffset阴影偏移,x向右偏移3，y向下偏移2，默认(0, -3),这个跟shadowRadius配合使用
    subLayer.shadowOpacity = shadowOpacity;//阴影透明度，默认0
    subLayer.shadowRadius = shadowRadius;//阴影半径，默认3
    [bgView.layer insertSublayer:subLayer below:view.layer];
    
    return bgView;
}
+ (UIView *)initViewWithFrame:(CGRect)frame backgroundColor:(UIColor *)color {
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = color;
    return view;
    
//    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
//    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//    maskLayer.frame = view.bounds;
//    maskLayer.path = maskPath.CGPath;
//    view.layer.mask = maskLayer;
}
+ (UIImageView *)initImageViewWithFrame:(CGRect)frame imageName:(NSString *)imageName {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    if (imageName) {
        imageView.image = [UIImage imageNamed:imageName];
    }
    return imageView;
}
+ (UIButton *)initButtonWithFrame:(CGRect)frame imageName:(NSString *)imageName target:(id)target action:(SEL)action title:(NSString *)title titleColor:(UIColor *)color {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    if (title) {
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    if (color) {
        [button setTitleColor:color forState:UIControlStateNormal];
    }
    if (imageName) {
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    return button;
}
+ (UITextField *)initTextFieldWithFrame:(CGRect)frame placeholder:(NSString *)placeholer secureTextEntry:(BOOL)YESorNO font:(CGFloat)font padding:(BOOL)padding {
    PSPaddingTextField *textField = [[PSPaddingTextField alloc] initWithFrame:frame];
    if (placeholer) {
        textField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:placeholer attributes:@{NSForegroundColorAttributeName:THEMECOLOR_OF_TEXT_cccccc}];
    }
    textField.textAlignment = NSTextAlignmentLeft;
    if (font) {
        textField.font = Font(font);
    }
    textField.textColor = THEMECOLOR_OF_TEXT_333333;
    textField.secureTextEntry = YESorNO;
    textField.autocapitalizationType = NO;
    textField.clearButtonMode = YES;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    textField.xPadding = ((padding)?(5*Scale):0);
    textField.yPadding = ((padding)?(5*Scale):0);
    
    return textField;
}
+ (UITableView *)initTableViewWithFrame:(CGRect)frame target:(id)target style:(UITableViewStyle)style {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:style];
    tableView.delegate = target;
    tableView.dataSource = target;
    return tableView;
}
+ (UICollectionView *)initCollectionViewWithFrame:(CGRect)frame target:(id)target collectionViewLayout:(UICollectionViewFlowLayout *)layout collectionViewCellID:(NSString *)cellID registerClass:(Class)registerClass {
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    [collectionView registerClass:registerClass forCellWithReuseIdentifier:cellID];
    collectionView.delegate = target;
    collectionView.dataSource = target;
    return collectionView;
}
+ (UITextView *)initTextViewWithFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)color font:(NSInteger)font editable:(BOOL)edit {
    UITextView *textView = [[UITextView alloc] initWithFrame:frame];
    textView.editable = edit;
    if (font) {
        textView.font = Font(font);
    }
    if (color) {
        textView.textColor = color;
    }
    if (text) {
        textView.text = text;
    }
    return textView;
}
#pragma mark - 画虚线
+ (CAShapeLayer *)drawDottedLine:(UIColor *)lineColor bounds:(CGRect)bounds position:(CGPoint)position {
    //设置虚线边框
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.bounds = bounds;
    //中心点位置
    borderLayer.position = position;
    borderLayer.path = [UIBezierPath bezierPathWithRect:bounds].CGPath;
    //边框的宽度
    borderLayer.lineWidth = 1;
    //边框虚线线段的宽度
    borderLayer.lineDashPattern = @[@3, @3];
    borderLayer.fillColor = COLOR_OF_CLEAR.CGColor;
    borderLayer.strokeColor = lineColor.CGColor;
    
    return borderLayer;
}

+ (CGFloat)textWidth:(NSString *)text size:(CGSize)size font:(CGFloat)font {
    NSInteger textWidth = ceil([text boundingRectWithSize:size options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:Font(font)} context:nil].size.width)+1;
    return textWidth;
}
+ (CGFloat)textHeight:(NSString *)text size:(CGSize)size font:(CGFloat)font {
    NSInteger textHeight = ceil([text boundingRectWithSize:size options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:Font(font)} context:nil].size.height)+1;
    return textHeight;
}
+ (CGFloat)textHeightWithLineSpacing:(NSString *)text size:(CGSize)size font:(CGFloat)font {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:LineSpacingHeight];
    
    NSInteger textHeight = ceil([text boundingRectWithSize:size options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:Font(font), NSParagraphStyleAttributeName:paragraphStyle} context:nil].size.height)+1;
    return textHeight;
}
+ (CGFloat)textHeightWithLineSpacing:(NSString *)text size:(CGSize)size boldFont:(CGFloat)font {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:LineSpacingHeight];
    
    NSInteger textHeight = ceil([text boundingRectWithSize:size options:(NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:FontBold(font), NSParagraphStyleAttributeName:paragraphStyle} context:nil].size.height)+1;
    
    return textHeight;
}

+ (void)buttonStype:(UIButton *)button select:(BOOL)select {
    if (select) {
        button.backgroundColor = COLOR_OF_WHITE;
        [button setTitleColor:THEMECOLOR_OF_RED forState:UIControlStateNormal];
    } else {
        button.backgroundColor = THEMECOLOR_OF_RED;
        [button setTitleColor:COLOR_OF_WHITE forState:UIControlStateNormal];
    }
}

+ (NSString *)getGender {
    NSString *returnStr = @"";
//    NSString *gender = UD_GetOForK(isGender);
//    if ([gender isEqualToString:@"1"]) {
//        returnStr = @"男";
//    } else {
//        returnStr = @"女";
//    }
    return returnStr;
}
#pragma mark - 处理数据，将数据转为string（无默认值）
+ (NSString *)dataAnalysis:(id)value {
    if (value) {
        if ([value isKindOfClass:[NSNull class]]) {
            return @"";
        } else {
            NSString *tempStr = [NSString stringWithFormat:@"%@", value];
            if (tempStr.length>0 && ![tempStr isEqualToString:isNullString]) {
                return tempStr;
            } else {
                return @"";
            }
        }
    } else {
        return @"";
    }
}
#pragma mark - 处理数据，将数据转为string(有默认值)
+ (NSString *)dataAnalysisHasDefault:(id)value {
    if (value) {
        if ([value isKindOfClass:[NSNull class]]) {
            return @"--";
        } else {
            NSString *tempStr = [NSString stringWithFormat:@"%@", value];
            if (tempStr.length>0 && ![tempStr isEqualToString:isNullString]) {
                return tempStr;
            } else {
                return @"--";
            }
        }
    } else {
        return @"--";
    }
}
#pragma mark - 处理价格相关数据，将数据转为string
+ (NSString *)dataAnalysisForPrice:(id)value {
    if (value) {
        if ([value isKindOfClass:[NSNull class]]) {
            return @"0";
        } else {
            NSString *tempStr = [NSString stringWithFormat:@"%@", value];
            if (tempStr.length>0 && ![tempStr isEqualToString:isNullString]) {
                return [NSString stringWithFormat:@"%@", [UIToolsControl reviseData:value]];
            } else {
                return @"0";
            }
        }
    } else {
        return @"0";
    }
}
#pragma mark - 处理bool类型数据(可能没有value)
+ (BOOL)dataAnalysisForBOOL:(id)value {
    if (value) {
        if ([value isKindOfClass:[NSNull class]]) {
            return NO;
        } else {
            return [value boolValue];
        }
    } else {
        return NO;
    }
}
#pragma mark - 将json字符串转json数据
+ (NSDictionary *)convertJsonStringToDict:(NSString *)jsonString {
    NSDictionary *retDict = @{};
    if ([jsonString isKindOfClass:[NSString class]]) {
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        retDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
    }
    return  retDict;
}

#pragma mark - 修正浮点型精度丢失
+ (NSString *)reviseData:(id)data {
    double conversionValue = [data doubleValue];
    NSString *doubleString = [NSString stringWithFormat:@"%lf", conversionValue];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}
#pragma mark - 加、减、乘、除、比较
+ (NSString *)decimalNumberArithmetic:(DecimalNumberArithmetic)arithmetic value1:(NSString *)value1 value2:(NSString *)value2 {
    //货币算法 使用NSDecimalNumber 来进行精准计算
    NSDecimalNumber *dNumber1 = [NSDecimalNumber decimalNumberWithString:value1];
    NSDecimalNumber *dNumber2 = [NSDecimalNumber decimalNumberWithString:value2];
    
    NSString *returnStr = @"";
    switch (arithmetic) {
        case DecimalNumberArithmeticByAdding: { // 加
            NSDecimalNumber *adding = [dNumber1 decimalNumberByAdding:dNumber2];
            returnStr = [adding stringValue];
        } break;
        case DecimalNumberArithmeticBySubtracting: { // 减
            NSDecimalNumber *subtracting = [dNumber1 decimalNumberBySubtracting:dNumber2];
            returnStr = [subtracting stringValue];
        } break;
        case DecimalNumberArithmeticByMultiplyingBy: { // 乘
            NSDecimalNumber *multiplyingBy = [dNumber1 decimalNumberByMultiplyingBy:dNumber2];
            returnStr = [multiplyingBy stringValue];
        } break;
        case DecimalNumberArithmeticByDividingBy: { // 除
            NSDecimalNumber *dividingBy = [dNumber1 decimalNumberByDividingBy:dNumber2];
            returnStr = [dividingBy stringValue];
        } break;
        case DecimalNumberArithmeticCompare: { // 比较大小
            NSComparisonResult result = [dNumber1 compare:dNumber2];
            if (result == NSOrderedAscending) { // 小于
                returnStr = @"-1";
            } else if (result == NSOrderedSame) { // 等于
                returnStr = @"0";
            } else if (result == NSOrderedDescending) { // 大于
                returnStr = @"1";
            }
        } break;
        default:
            break;
    }
    return returnStr;
}

/*#define LineSpacingHeight (3*Scale)
#pragma mark - RSA加密
+ (NSString *)rsaEncryptString:(NSString *)string {
    RSAEncryptor *rsa = [[RSAEncryptor alloc] init];
    NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
    [rsa loadPublicKeyFromFile:publicKeyPath];
    NSString *encryptedString = [rsa rsaEncryptString:string];
    return encryptedString;
}
#pragma mark - RSA解密
+ (NSString *)rsaDecryptString:(NSString *)string {
    RSAEncryptor *rsa = [[RSAEncryptor alloc] init];
    NSString *privateKeyPath = [[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"p12"];
    [rsa loadPrivateKeyFromFile:privateKeyPath password:@"1"];
    NSString *decryptString = [rsa rsaDecryptString:string];
    return decryptString;
}
*/

#pragma mark - 请求数据Request
+ (NSMutableURLRequest *)postUrlString:(NSString *)urlString withParameterString:(NSString *)parameterString {
    NSData *data = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy  timeoutInterval:10];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: data];
    [request setValue:@"application/octet-stream;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    return request;
}

#pragma mark - 获取验证码上传的类型
+ (NSString *)getCaptchaType:(GetCaptchaType)getCaptchaType {
    NSString *returnStr = @"";
    switch (getCaptchaType) {
        case GetCaptchaTypeOfRegister: {
            returnStr = @"reg";
        } break;
        case GetCaptchaTypeOfSignin: {
            returnStr = @"login";
        } break;
        case GetCaptchaTypeOfChangePassword: {
            returnStr = @"reset_pwd";
        } break;
        case GetCaptchaTypeOfChangeAccount: {
            returnStr = @"bind";
        } break;
        default:
            break;
    }
    return returnStr;
}
#pragma mark - 获取验证码
+ (void)getCaptcha:(NSString *)phone countryCode:(NSString *)countryCode type:(NSString *)getCaptchaType successBlock:(requestSuccessBlock)success {
    // 类型type:  reg-注册帐号 login-登录帐号 reset_pwd-重置密码 bind-换绑帐号
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:phone forKey:@"mobile"];
    [dic setObject:getCaptchaType forKey:@"type"];
//    [dic setObject:countryCode forKey:@"country_code"];
    
//    [[BaseNetManager sharedManager] requestWithMethod:GET path:GetCaptcha_URL params:dic successBlock:^(NSDictionary *responseObject) {
//        if (([responseObject[@"status"] integerValue] == 0) && ([responseObject[@"error"] integerValue] == 0)) {
//            SVPHUDSuccess(CaptchaSuccessAlertText);
//            success(responseObject);
//        } else {
//            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
//            SVPHUDError(str);
//        }
//    } failurBlock:^(NSError *error) {
//        SVPHUDError(NetErrorAlertText);
//    }];
    [BaseNetManager requestWithMethod:POST path:GetCaptcha_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if (([responseObject[@"status"] integerValue] == 0) && ([responseObject[@"error"] integerValue] == 0)) {
            SVPHUDSuccess(CaptchaSuccessAlertText);
            success(responseObject);
        } else {
            NSString *str = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            SVPHUDError(str);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

#pragma mark - 正则判断输入的手机号是否有效
+ (BOOL)validatePhoneNumber:(NSString *)textString {
    return [UIToolsControl validateNumber:textString];
    /**
     * 正则：手机号（精确）
     * <p>移动：134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188、198</p>
     * <p>联通：130、131、132、145、155、156、175、176、185、186、166</p>
     * <p>电信：133、153、173、177、180、181、189、199</p>
     * <p>全球星：1349</p>
     * <p>虚拟运营商：170</p>
     */
    //    NSString *phoneNumber = @"^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
    //    NSString *phoneNumber = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    NSString *phoneNumber = @"[1][3456789]\\d{9}";
    NSPredicate *phoneNumberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumber];
    return [phoneNumberPre evaluateWithObject:textString];
}
#pragma mark - 正则判断输入的是不是QQ号
+ (BOOL)validateQQ:(NSString *)textString {
    NSString *number= @"^[1-9][0-9]{5,14}";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", number];
    return [numberPre evaluateWithObject:textString];
}

#pragma mark - 正则判断输入的是不是数字
+ (BOOL)validateNumber:(NSString *)textString {
    // 数字、小数
//    NSString *number = @"^[0-9].*$";
    // 数字
//    NSString *number=@"^[0-9]*$";
    // 数字，非负数
//    NSString *number= @"((^[1-9]\\d*)|^0)(\\.\\d+){0,1}$";
    // 数字
    NSString *number= @"^\\d+$";
    
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", number];
    return [numberPre evaluateWithObject:textString];
}
#pragma mark - 正则判断输入的是不是非0正整数
+ (BOOL)validatePositiveInteger:(NSString *)textString {
    NSString *number= @"^(?!0)\\d+$";
    
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", number];
    return [numberPre evaluateWithObject:textString];
}
#pragma mark - 正则判断输入的是不是中、英文、数字
+ (BOOL)validateENOrEnglishOrNumber:(NSString *)textString {
    NSString *number = @"^[a-zA-Z0-9\u4e00-\u9fa5]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}
#pragma mark - 正则判断输入的是不是整数
+ (BOOL)validateInteger:(NSString *)textString {
    NSString *integer = @"^[0-9]*[1-9][0-9]*$";
    NSPredicate *integerPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",integer];
    return [integerPre evaluateWithObject:textString];
}
#pragma mark - 正则判断输入的是不是数字字母
+ (BOOL)validateNumberAndLetter:(NSString *)textString {
    NSString *numberAndLetter = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";
    NSPredicate *numberAndLetterPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberAndLetter];
    return [numberAndLetterPre evaluateWithObject:textString];
}
#pragma mark - 正则判断输入的是不是邮箱
+ (BOOL)validateEmail:(NSString *)textString {
//    NSString *email = [NSString stringWithFormat:@"/^[a-z0-9A-Z]+[-|a-z0-9A-Z._]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\%@)+[a-z]{2,}$/", @"."];
//    NSPredicate *emailPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", email];
//    return [emailPre evaluateWithObject:textString];
    
    return YES;
}
#pragma mark - 正则判断输入的是不是身份证号
+ (BOOL)validateIDCard:(NSString *)textString {
    NSString *numberAndLetter = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *numberAndLetterPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",numberAndLetter];
    return [numberAndLetterPre evaluateWithObject:textString];
}

#pragma mark - 处理手机号（中间四位*表示）
+ (NSString *)handlePhoneNumber:(NSString *)phoneNumber {
    NSString *numberString = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    return numberString;
}
#pragma mark - 密码MD5加密
+ (NSString *)MD5DataEncryption:(NSString *)string {
    if (string == nil || [string length] == 0) {
        return nil;
    }
    unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
    CC_MD5([string UTF8String], (int)[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest);
    NSMutableString *ms = [NSMutableString string];
    
    for (i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ms appendFormat:@"%02x", (int)(digest[i])];
    }
    return [ms copy];
}
#pragma mark - 生成二维码
+ (UIImage *)generateQRCode:(NSString *)content {
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];
    CIImage *ciImage = [filter outputImage];
    UIImage * image = [self createNonInterpolatedUIImageFormCIImage:ciImage withResolution:QRCodeResolution];
    return image;
}
#pragma mark - 处理图片
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withResolution:(CGFloat)resolution {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(resolution/CGRectGetWidth(extent), resolution/CGRectGetHeight(extent));
    
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
#pragma mark - 获取截图
+ (UIImage *)getImageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 自定义Image
+ (UIImage *)getCustomImageWithRect:(CGRect)rect color:(UIColor *)color {
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 重新设置image的size
+ (UIImage *)imageResize:(UIImage *)image size:(CGSize)newSize {
    CGFloat scale = [[UIScreen mainScreen] scale];
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - 数组数据反转
+ (NSArray *)returnReverseObject:(NSArray *)array {
    return [[array reverseObjectEnumerator] allObjects];
}


#pragma mark - 时间戳转化成时间
+ (NSString *)timestampConversionTime:(NSInteger)timestamp andFormat:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}
#pragma mark - 获取当前的时间 yyyy-MM-dd
+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *nowDate = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:nowDate];
    return currentTimeString;
}
#pragma mark - 获取当前时间戳
+ (NSString *)getCurrentTimestamp {
    NSDate *date = [NSDate date];
    NSTimeInterval timeInt = [date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", timeInt];
    return timeString;
}
#pragma mark - 时间字符串转时间戳
+ (NSInteger)stringConversiontimeStamp:(NSString *)string {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:string];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    NSInteger returnInt = [timeSp integerValue];
    return returnInt;
}

#pragma mark - 公共参数
+ (NSMutableDictionary *)getPublicParameter {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *token = UD_GetOForK(isToken);
    if (token && token.length>0) {
    } else {
        token = @"";
    }
    [dic addEntriesFromDictionary:@{@"token":token,
                                    @"os_type":@"iOS",
                                    @"os_version":[self getSystemVersion],
                                    @"app_version":[self getVersionAndBuild],
                                    @"app_language":@"1",
                                    @"timestamp":[self getCurrentTimestamp],
                                    @"device_id":[self getUUID],
                                    @"device_brand":@"Apple",
                                    @"device_model":[self getDeviceModel],
                                    @"screen_width":[NSNumber numberWithFloat:WIDTH*[UIScreen mainScreen].scale],
                                    @"screen_height":[NSNumber numberWithFloat:HEIGHT*[UIScreen mainScreen].scale]}];
    return dic;
}
#pragma mark - 获取系统版本号
+ (NSString *)getSystemVersion {
    NSString *version = [UIDevice currentDevice].systemVersion;
    return version;
}
#pragma mark - 获取UUID
+ (NSString *)getUUID {
    NSString *returnString = @"";
    return returnString = [[UIDevice currentDevice].identifierForVendor UUIDString];
}
#pragma mark - 获取app name
+ (NSString *)getAppName {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    return name;
}
#pragma mark - 获取版本信息 version.build
+ (NSString *)getVersionAndBuild {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSString *returnStr = returnStr = [NSString stringWithFormat:@"v%@.%@", app_Version, app_build];
    return returnStr;
}
#pragma mark - 获取版本信息 version
+ (NSString *)getVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
#pragma mark - 获取设备型号
+ (NSString *)getDeviceModel {
    // 需要#import <sys/utsname.h>
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceModel isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([deviceModel isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([deviceModel isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([deviceModel isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([deviceModel isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([deviceModel isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([deviceModel isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([deviceModel isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
// 日行两款手机型号均为日本独占，可能使用索尼FeliCa支付方案而不是苹果支付
    if ([deviceModel isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,4"]) return @"iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    if ([deviceModel isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    if ([deviceModel isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    if ([deviceModel isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    if ([deviceModel isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([deviceModel isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if ([deviceModel isEqualToString:@"iPhone11,4"] ||
        [deviceModel isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    if ([deviceModel isEqualToString:@"iPhone12,1"]) return @"iPhone 11";
    if ([deviceModel isEqualToString:@"iPhone12,3"]) return @"iPhone 11 Pro";
    if ([deviceModel isEqualToString:@"iPhone12,5"]) return @"iPhone 11 Pro Max";
    if ([deviceModel isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
    if ([deviceModel isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
    if ([deviceModel isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
    if ([deviceModel isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
    if ([deviceModel isEqualToString:@"iPod5,1"]) return @"iPod Touch (5 Gen)";
    if ([deviceModel isEqualToString:@"iPod7,1"]) return @"iPod Touch (6 Gen)";
    if ([deviceModel isEqualToString:@"iPod9,1"]) return @"iPod Touch (7 Gen)";
    if ([deviceModel isEqualToString:@"iPad1,1"]) return @"iPad";
    if ([deviceModel isEqualToString:@"iPad1,2"]) return @"iPad 3G";
    if ([deviceModel isEqualToString:@"iPad2,1"]) return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,2"]) return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,3"]) return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,4"]) return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,5"]) return @"iPad Mini";
    if ([deviceModel isEqualToString:@"iPad2,6"]) return @"iPad Mini";
    if ([deviceModel isEqualToString:@"iPad2,7"]) return @"iPad Mini";
    if ([deviceModel isEqualToString:@"iPad3,1"]) return @"iPad 3";
    if ([deviceModel isEqualToString:@"iPad3,2"]) return @"iPad 3";
    if ([deviceModel isEqualToString:@"iPad3,3"]) return @"iPad 3";
    if ([deviceModel isEqualToString:@"iPad3,4"]) return @"iPad 4";
    if ([deviceModel isEqualToString:@"iPad3,5"]) return @"iPad 4";
    if ([deviceModel isEqualToString:@"iPad3,6"]) return @"iPad 4";
    if ([deviceModel isEqualToString:@"iPad4,1"]) return @"iPad Air";
    if ([deviceModel isEqualToString:@"iPad4,2"]) return @"iPad Air";
    if ([deviceModel isEqualToString:@"iPad4,4"]) return @"iPad Mini 2";
    if ([deviceModel isEqualToString:@"iPad4,5"]) return @"iPad Mini 2";
    if ([deviceModel isEqualToString:@"iPad4,6"]) return @"iPad Mini 2";
    if ([deviceModel isEqualToString:@"iPad4,7"]) return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,8"]) return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,9"]) return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad5,1"]) return @"iPad Mini 4";
    if ([deviceModel isEqualToString:@"iPad5,2"]) return @"iPad Mini 4";
    if ([deviceModel isEqualToString:@"iPad5,3"]) return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad6,3"]) return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,7"]) return @"iPad Pro 12.9";
    if ([deviceModel isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9";
    if ([deviceModel isEqualToString:@"iPad6,11"] || [deviceModel isEqualToString:@"iPad6,12"]) return @"iPad 2017";
    if ([deviceModel isEqualToString:@"iPad7,1"]) return @"iPad Pro 2nd Gen (WiFi)";
    if ([deviceModel isEqualToString:@"iPad7,2"]) return @"iPad Pro 2nd Gen (WiFi+Cellular)";
    if ([deviceModel isEqualToString:@"iPad7,3"] || [deviceModel isEqualToString:@"iPad7,4"]) return @"iPad Pro 10.5-inch";
    if ([deviceModel isEqualToString:@"iPad7,5"]) return @"iPad 6th Gen (WiFi)";
    if ([deviceModel isEqualToString:@"iPad7,6"]) return @"iPad 6th Gen (WiFi+Cellular)";
    if ([deviceModel isEqualToString:@"iPad8,1"]) return @"iPad Pro 3rd Gen (11 inch, WiFi)";
    if ([deviceModel isEqualToString:@"iPad8,2"]) return @"iPad Pro 3rd Gen (11 inch, 1TB, WiFi)";
    if ([deviceModel isEqualToString:@"iPad8,3"]) return @"iPad Pro 3rd Gen (11 inch, WiFi+Cellular)";
    if ([deviceModel isEqualToString:@"iPad8,4"]) return @"iPad Pro 3rd Gen (11 inch, 1TB, WiFi+Cellular)";
    if ([deviceModel isEqualToString:@"iPad8,5"]) return @"iPad Pro 3rd Gen (12.9 inch, WiFi)";
    if ([deviceModel isEqualToString:@"iPad8,6"]) return @"iPad Pro 3rd Gen (12.9 inch, 1TB, WiFi)";
    if ([deviceModel isEqualToString:@"iPad8,7"]) return @"iPad Pro 3rd Gen (12.9 inch, WiFi+Cellular)";
    if ([deviceModel isEqualToString:@"iPad8,8"]) return @"iPad Pro 3rd Gen (12.9 inch, 1TB, WiFi+Cellular)";
    if ([deviceModel isEqualToString:@"iPad11,1"]) return @"iPad mini 5th Gen (WiFi)";
    if ([deviceModel isEqualToString:@"iPad11,2"]) return @"iPad mini 5th Gen";
    if ([deviceModel isEqualToString:@"iPad11,3"]) return @"iPad Air 3rd Gen (WiFi)";
    if ([deviceModel isEqualToString:@"iPad11,4"]) return @"iPad Air 3rd Gen";
    
    if ([deviceModel isEqualToString:@"AppleTV2,1"]) return @"Apple TV 2";
    if ([deviceModel isEqualToString:@"AppleTV3,1"]) return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV3,2"]) return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV5,3"]) return @"Apple TV 4";
    
    if ([deviceModel isEqualToString:@"i386"]) return @"Simulator";
    if ([deviceModel isEqualToString:@"x86_64"]) return @"Simulator";
    return deviceModel;
}
/*{
     // 需要#import <sys/utsname.h>
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceModel isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([deviceModel isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
    if ([deviceModel isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
    if ([deviceModel isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([deviceModel isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([deviceModel isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    // 日行两款手机型号均为日本独占，可能使用索尼FeliCa支付方案而不是苹果支付
    if ([deviceModel isEqualToString:@"iPhone9,1"]) return @"国行、日版、港行iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,2"]) return @"港行、国行iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone9,3"]) return @"美版、台版iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,4"]) return @"美版、台版iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,1"]) return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,4"]) return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,2"]) return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,5"]) return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,3"]) return @"iPhone_X";
    if ([deviceModel isEqualToString:@"iPhone10,6"]) return @"iPhone_X";
    if ([deviceModel isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([deviceModel isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if ([deviceModel isEqualToString:@"iPhone11,4"] ||
    [deviceModel isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    if ([deviceModel isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
    if ([deviceModel isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
    if ([deviceModel isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
    if ([deviceModel isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
    if ([deviceModel isEqualToString:@"iPod5,1"]) return @"iPod Touch (5 Gen)";
    if ([deviceModel isEqualToString:@"iPad1,1"]) return @"iPad";
    if ([deviceModel isEqualToString:@"iPad1,2"]) return @"iPad 3G";
    if ([deviceModel isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad2,2"]) return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
    if ([deviceModel isEqualToString:@"iPad2,4"]) return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
    if ([deviceModel isEqualToString:@"iPad2,6"]) return @"iPad Mini";
    if ([deviceModel isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad3,3"]) return @"iPad 3";
    if ([deviceModel isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad3,5"]) return @"iPad 4";
    if ([deviceModel isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
    if ([deviceModel isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
    if ([deviceModel isEqualToString:@"iPad4,4"]) return @"iPad Mini 2 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad4,5"]) return @"iPad Mini 2 (Cellular)";
    if ([deviceModel isEqualToString:@"iPad4,6"]) return @"iPad Mini 2";
    if ([deviceModel isEqualToString:@"iPad4,7"]) return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,8"]) return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,9"]) return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad5,1"]) return @"iPad Mini 4 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad5,2"]) return @"iPad Mini 4 (LTE)";
    if ([deviceModel isEqualToString:@"iPad5,3"]) return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad6,3"]) return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,7"]) return @"iPad Pro 12.9";
    if ([deviceModel isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9";
    
    if ([deviceModel isEqualToString:@"AppleTV2,1"]) return @"Apple TV 2";
    if ([deviceModel isEqualToString:@"AppleTV3,1"]) return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV3,2"]) return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV5,3"]) return @"Apple TV 4";
    
    if ([deviceModel isEqualToString:@"i386"]) return @"Simulator";
    if ([deviceModel isEqualToString:@"x86_64"]) return @"Simulator";
    return deviceModel;
}
*/

#pragma mark - 判断系统版本号
+ (BOOL)iOSVersion8 {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) ? YES : NO);
}
+ (BOOL)iOSVersion9 {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) ? YES : NO);
}
+ (BOOL)iOSVersion10 {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) ? YES : NO);
}
+ (BOOL)iOSVersion11 {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0) ? YES : NO);
}
+ (BOOL)iOSVersion12 {
    return (([[[UIDevice currentDevice] systemVersion] floatValue] >= 12.0) ? YES : NO);
}
//判断文件是否已经在沙盒中存在
+ (BOOL)isFileExist:(NSString *)fileName {
//    NSString *fileNameStr = fileName;
//    if (Signin) {
//        fileNameStr = [NSString stringWithFormat:@"%@/%@", isUserID, fileName];
//    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *path = [paths objectAtIndex:0];
    NSString *path = [paths lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}
#pragma mark - 计算时间差
+ (NSString *)calculateCallTimeWithStartTime:(NSString *)startTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy_MM_dd__HH_mm_ss"];
    NSDate *nowDate = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
    NSDate *beginDate = [formatter dateFromString:startTime];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    //对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:beginDate toDate:nowDate options:0];
    NSString *callTime;
    
    NSInteger hours =  dateCom.hour;
    NSInteger minute = dateCom.minute;
    NSInteger second = dateCom.second;
    
    if (hours != 0) {
        callTime = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours,(long)minute,(long)second];
    } else {
        callTime = [NSString stringWithFormat:@"%02ld:%02ld",(long)minute,(long)second];
    }
    return callTime;
}

#pragma amrk - 模态跳转登录页面
+ (void)presentSignin:(id)target callBack:(signinCallback)signin {
    SigninViewController *SVC = [[SigninViewController alloc] init];
    SVC.signin = ^(BOOL signinFlag) {
        signin(signinFlag);
    };
    RootNavigationController *nav = [[RootNavigationController alloc] initWithRootViewController:SVC];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [target presentViewController:nav animated:NO completion:nil];
}
#pragma mark - 判断手机有哪些平台
+ (NSMutableArray *)returnShareArray {
//    NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:0];
//    if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_WechatSession]) {
//        [returnArray addObject:@(UMSocialPlatformType_WechatSession)];
//    }
//    if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_WechatTimeLine]) {
//        [returnArray addObject:@(UMSocialPlatformType_WechatTimeLine)];
//    }
//    if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_QQ]) {
//        [returnArray addObject:@(UMSocialPlatformType_QQ)];
//    }
//    if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_Sina]) {
//        [returnArray addObject:@(UMSocialPlatformType_Sina)];
//    }
//    return returnArray;
    
    return nil;
}
#pragma Mark - 设置友盟分享面板
+ (void)UMShareAppearance {
//    NSArray *tempArray = [UIToolsControl returnShareArray];
//    [UMSocialUIManager setPreDefinePlatforms:tempArray];
//
//    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageItemStyleType = UMSocialPlatformItemViewBackgroudType_None;
//    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxRowCountForPortraitAndBottom = 1;
//    [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
//    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.shareTitleViewTitleString = @"分享给好友";
    
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_WechatSession withPlatformIcon:[UIImage imageNamed:@"share_wechat"] withPlatformName:@"微信好友"];
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_WechatTimeLine withPlatformIcon:[UIImage imageNamed:@"share_moments"] withPlatformName:@"朋友圈"];
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_QQ withPlatformIcon:[UIImage imageNamed:@"share_qq"] withPlatformName:@"QQ好友"];
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_Sina withPlatformIcon:[UIImage imageNamed:@"share_weibo"] withPlatformName:@"微博"];
}



#pragma mark - 归档
+ (void)archiver:(NSArray *)data path:(NSString *)path {
    BOOL result = [NSKeyedArchiver archiveRootObject:data toFile:path];
    if (result) {
        NSLog(@"归档成功:%@", path);
    } else {
        NSLog(@"归档不成功!!!");
    }
}
#pragma mark - 解档
+ (NSMutableArray *)unArchiverPath:(NSString *)path {
    NSArray *tempArr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:0];
    if (tempArr.count>0) {
        [returnArray addObjectsFromArray:tempArr];
    }
    return returnArray;
}
#pragma mark - 处理快讯缓存数据
+ (void)archiverCacheData {
//    if ([[DataManager sharedManager].channelCacheDataArray count]>0) {
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        if ([fileManager fileExistsAtPath:ChannelCacheDataPath]) {
//            if ([fileManager removeItemAtPath:ChannelCacheDataPath error:nil]) {
//                NSLog(@"dele success");
//                [UIToolsControl archiver:[DataManager sharedManager].channelCacheDataArray path:ChannelCacheDataPath];
//            } else {
//                NSLog(@"dele fail");
//            }
//        } else {
//            [UIToolsControl archiver:[DataManager sharedManager].channelCacheDataArray path:ChannelCacheDataPath];
//        }
//    }
}

+ (NSString *)returnDataName:(NSArray<PublicCategoryElementModel *> *)arr id:(NSString *)ID {
    for (PublicCategoryElementModel *model in arr) {
        if ([model.id isEqualToString:ID]) {
            return model.name;
            break;
        }
    }
    return @"";
}
#pragma mark - 移除第一响应
+ (void)resignFirstResponderForTextField:(UITextField *)textField {
    if (textField.isFirstResponder) {
        [textField resignFirstResponder];
    }
}
+ (void)resignFirstResponderForTextFieldArray:(NSArray<UITextField *> *)dataArray {
    for (UITextField *textField in dataArray) {
        [UIToolsControl resignFirstResponderForTextField:textField];
    }
}

#pragma mark - 有没有安装微信
+ (BOOL)canOpenWXApp {
    return [WXApi isWXAppInstalled];
}
#pragma mark - 微信分享--文本
+ (void)wxShareText:(NSString *)text shareType:(ShareType)shareType {
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = YES;
    req.text = text;
//    req.scene = WXSceneSession;
    switch (shareType) {
        case ShareTypeOfWXHaoyou: {
            req.scene = WXSceneSession;
        } break;
        case ShareTypeOfWXPengyouquan: {
            req.scene = WXSceneTimeline;
        } break;
        default:
            break;
    }
    [WXApi sendReq:req completion:^(BOOL success) {
        
    }];
//    [WXApi sendReq:req];
}
#pragma mark - 微信分享--图片
+ (void)wxShareImg:(UIImage *)img shareType:(ShareType)shareType {
    UIImage *image = img;
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = imageData;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.thumbData = UIImagePNGRepresentation([UIImage imageNamed:@"logo_icon"]);
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
//    req.scene = WXSceneSession;
    switch (shareType) {
        case ShareTypeOfWXHaoyou: {
            req.scene = WXSceneSession;
        } break;
        case ShareTypeOfWXPengyouquan: {
            req.scene = WXSceneTimeline;
        } break;
        default:
            break;
    }
    [WXApi sendReq:req completion:^(BOOL success) {
        
    }];
//    [WXApi sendReq:req];
}
#pragma mark - 微信分享--链接
+ (void)wxShareWebURL:(NSString *)url title:(NSString *)title desc:(NSString *)desc thumbUrl:(NSString *)thumbUrl shareType:(ShareType)shareType {
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = url;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = desc;
    if ((thumbUrl&&thumbUrl.length)) {
        UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbUrl]]];
        if (img) {
            message.thumbData = UIImagePNGRepresentation(img);
        } else {
            message.thumbData = UIImagePNGRepresentation([UIImage imageNamed:@"logo_icon"]);
        }
    } else {
        message.thumbData = UIImagePNGRepresentation([UIImage imageNamed:@"logo_icon"]);
    }
    message.mediaObject = webpageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
//    req.scene = WXSceneSession;
    switch (shareType) {
        case ShareTypeOfWXHaoyou: {
            req.scene = WXSceneSession;
        } break;
        case ShareTypeOfWXPengyouquan: {
            req.scene = WXSceneTimeline;
        } break;
        default:
            break;
    }
    [WXApi sendReq:req completion:^(BOOL success) {
        
    }];
//    [WXApi sendReq:req];
}
#pragma mark - 判断有没有安装QQ
+ (BOOL)canOpenQQApp {
    return [QQApiInterface isQQInstalled];
}
#pragma mark - QQ分享--文本
+ (void)qqShareText:(NSString *)text shareType:(ShareType)shareType {
    QQApiTextObject *textObj = [QQApiTextObject objectWithText:text];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:textObj];
    switch (shareType) {
        case ShareTypeOfQQ: { //将内容分享到qq
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        } break;
        case ShareTypeOfQQZone: { //将内容分享到qzone
            QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
        } break;
        default:
            break;
    }
}
#pragma mark - QQ分享--图片
+ (void)qqShareImg:(UIImage *)img title:(NSString *)title desc:(NSString *)desc shareType:(ShareType)shareType {
    UIImage *image = img;
    NSData *imageDataBig = UIImageJPEGRepresentation(image, 0.7);
    NSData *imageDataSmail = UIImageJPEGRepresentation(image, 0.2);
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imageDataBig previewImageData:imageDataSmail title:title description:desc];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imgObj];
    switch (shareType) {
        case ShareTypeOfQQ: { //将内容分享到qq
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        } break;
        case ShareTypeOfQQZone: { //将内容分享到qzone
            QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
        } break;
        default:
            break;
    }
}
#pragma mark - QQ分享--链接
+ (void)qqShareWebURL:(NSString *)url title:(NSString *)title desc:(NSString *)desc thumbUrl:(NSString *)thumbUrl shareType:(ShareType)shareType {
    QQApiNewsObject *newsObj = [QQApiNewsObject
                                objectWithURL:[NSURL URLWithString:url]
                                title:title
                                description:desc
                                previewImageURL:[NSURL URLWithString:thumbUrl]];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
    switch (shareType) {
        case ShareTypeOfQQ: { //将内容分享到qq
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
            NSLog(@"%d", sent);
        } break;
        case ShareTypeOfQQZone: { //将内容分享到qzone
            QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
        } break;
        default:
            break;
    }
}


/**
 视图截图
 */
+ (UIImage *)snapshot:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:view.bounds cornerRadius:5].CGPath);
    [view drawRect:view.bounds];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/**
 保存相册
 */
+ (void)savePhotos:(UIImage *)image{
    ALAssetsLibrary * library = [ALAssetsLibrary new];
    NSData *data = UIImagePNGRepresentation(image);
    [library writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:nil];
}

/**
 时间转换月-日
 */
+ (NSString *)conversionMonthAndDay:(NSString *)time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSDate *timeDate = [dateFormatter dateFromString:time];
    
    NSDateFormatter * format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MM月dd日"];
    NSString *currentTime = [format stringFromDate:timeDate];
    return currentTime;
}

/**
 时间转换月-日-时-分 当天显示时分
 */
+ (NSString *)conversionMonthDayHoursMinuteOrHoursMinute:(NSInteger)timeInteger{
    NSDate *date  = [NSDate dateWithTimeIntervalSince1970:timeInteger];
    NSDateFormatter * format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MM月dd日"];
    
    NSString *currentTime = [format stringFromDate:date];
    NSString *todayTime = [format stringFromDate:[NSDate date]];
    if ([currentTime isEqualToString:todayTime]) {
        [format setDateFormat:@"HH:mm"];
        currentTime = [format stringFromDate:date];
        return currentTime;
    }else{
        [format setDateFormat:@"yyyy年MM月dd日 HH:mm"];
        currentTime = [format stringFromDate:date];
        return currentTime;
    }
}

//余额显示规则控制
+ (NSString *)showAmount:(NSString *)str{
    if ([[str substringFromIndex:str.length-2] isEqualToString:@"00"]) {
        str = [str substringToIndex:str.length-3];
    }else if ([[str substringFromIndex:str.length-1] isEqualToString:@"0"]){
        str = [str substringToIndex:str.length-1];
    }
    return str;
}

/**
 
 获取url中的参数并返回
 @param urlString 带参数的url
 @return @{NSDictionary:参数字典}
 */
+ (NSDictionary *)getParamsWithUrlString:(NSString*)urlString{
    
    if(urlString.length==0) {
        NSLog(@"链接为空！");
        return @{};
    }
    
    //先截取问号
    NSArray*allElements = [urlString componentsSeparatedByString:@"?"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];//待set的参数字典
    if(allElements.count==2) {
        //有参数或者?后面为空
//        NSString*myUrlString = allElements[0];
        NSString*paramsString = allElements[1];
        //获取参数对
        NSArray*paramsArray = [paramsString componentsSeparatedByString:@"&"];
        if(paramsArray.count>=2) {
            for(NSInteger i = 0; i < paramsArray.count; i++) {
                NSString *singleParamString = paramsArray[i];
                NSArray*singleParamSet = [singleParamString componentsSeparatedByString:@"="];
                if(singleParamSet.count==2) {
                    NSString*key = singleParamSet[0];
                    NSString*value = singleParamSet[1];
                    if(key.length>0|| value.length>0) {
                        [params setObject:value.length>0?value:@""forKey:key.length>0?key:@""];
                    }
                }
            }
        }else if(paramsArray.count==1) {
            //无 &。url只有?后一个参数
            NSString*singleParamString = paramsArray[0];
            NSArray*singleParamSet = [singleParamString componentsSeparatedByString:@"="];
            if(singleParamSet.count==2) {
                NSString*key = singleParamSet[0];
                NSString*value = singleParamSet[1];
                if(key.length>0|| value.length>0) {
                    [params setObject:value.length>0?value:@""forKey:key.length>0?key:@""];
                }
            }else{
                //问号后面啥也没有 xxxx?  无需处理
            }
        }
        //整合url及参数
        return params;
    }else if(allElements.count>2) {
        NSLog(@"链接不合法！链接包含多个\"?\"");
        return @{};
    }else{
        NSLog(@"链接不包含参数！");
        return @{};
    }
}

//转码方法
+ (NSString*)URLDecodedString:(NSString*)str{
    str = [str stringByReplacingOccurrencesOfString:@"+" withString:@" "];
//    NSString *decodedString = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *decodedString = [str stringByRemovingPercentEncoding];
    return decodedString;
}


//比较时间 YES 表示结束时间大于起始时间 NO相反
+ (BOOL)comparisonLatterStarTime:(NSString *)startime endTime:(NSString *)endtime{
    NSDateFormatter * format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM"];
    NSString *todayTime = [format stringFromDate:[NSDate date]];
    if ([endtime isEqualToString:@"至今"]) {
        endtime = todayTime;
    }
    
    NSArray *startArray = [startime componentsSeparatedByString:@"-"];
    NSString *startYear = startArray[0];
    NSString *starMonth = startArray[1];
    
    NSArray *endArray = [endtime componentsSeparatedByString:@"-"];
    NSString *endYear = endArray[0];
    NSString *endMonth = endArray[1];
    
    if ([startYear integerValue] < [endYear integerValue]) {
        return YES;
    }else if ([startYear integerValue] > [endYear integerValue]) {
        return NO;
    }else{
        if ([starMonth integerValue] < [endMonth integerValue]) {
            return YES;
        }else{
            return NO;
        }
    }
}


@end
